import React, { useState, useRef } from "react";

// 定义滑块验证组件的属性类型
// 滑块验证组件
const SlideVerify = ({ onVerify }) => {
  // 状态管理
  const [isVerified, setIsVerified] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const [position, setPosition] = useState(0);

  // 引用管理
  const sliderRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const blockRef = useRef<HTMLDivElement>(null);

  // 生成随机拼图位置（50-200之间）
  const [puzzlePosition] = useState(Math.floor(Math.random() * 150) + 50);

  // 开始拖动处理函数
  const handleDragStart = (e) => {
    if (isVerified) return;
    setIsDragging(true);
  };

  // 拖动过程处理函数
  const handleDrag = (e) => {
    if (!isDragging) return;

    // 计算滑块位置
    const trackWidth = trackRef.current?.clientWidth || 0;
    const sliderWidth = sliderRef.current?.clientWidth || 0;
    const maxPosition = trackWidth - sliderWidth;

    let newPosition = 0;

    if (e.type === "touchmove") {
      const touchEvent = e as TouchEvent<HTMLDivElement>;
          const touch = touchEvent.touches[0];
      const rect = trackRef.current?.getBoundingClientRect() || { left: 0 };
      newPosition = touch.clientX - rect.left - sliderWidth / 2;
    } else {
      const mouseEvent = e as MouseEvent<HTMLDivElement>;
          const rect = trackRef.current?.getBoundingClientRect() || { left: 0 };
          newPosition = mouseEvent.clientX - rect.left - sliderWidth / 2;
    }

    // 限制滑块在轨道内
    newPosition = Math.max(0, Math.min(newPosition, maxPosition));
    setPosition(newPosition);
  };

  // 结束拖动，验证结果
  const handleDragEnd = (e) => {
    if (!isDragging) return;
    setIsDragging(false);

    // 验证拼图位置是否接近目标位置
    const tolerance = 10; // 容差范围
    if (Math.abs(position - puzzlePosition) <= tolerance) {
      setIsVerified(true);
      onVerify(true);
    } else {
      // 验证失败，重置位置
      setTimeout(() => {
        setPosition(0);
      }, 300);
      onVerify(false);
    }
  };

  // 样式计算
  const sliderStyle = {
    transform: `translateX(${position}px)`,
    transition: isDragging ? "none" : "transform 0.3s ease",
  };

  const blockStyle = {
    left: `${puzzlePosition}px`,
    transform: `translateX(${position}px)`,
    transition: isDragging ? "none" : "transform 0.3s ease",
  };

  return (
    <div className="slide-verify-container">
      {/* 背景图 */}
      <div className="slide-verify-bg">
        <div className="slide-verify-block" style={blockStyle} ref={blockRef} />
      </div>

      {/* 滑块轨道 */}
      <div className="slide-verify-track" ref={trackRef}>
        {/* 滑块 */}
        <div
          className={`slide-verify-slider ${isVerified ? "verified" : ""}`}
          style={sliderStyle}
          ref={sliderRef}
          onMouseDown={handleDragStart}
          onTouchStart={handleDragStart}
        >
          {isVerified ? (
            <i className="fa fa-check" />
          ) : isDragging ? (
            <i className="fa fa-hand-paper-o" />
          ) : (
            <i className="fa fa-arrow-right" />
          )}
        </div>

        {/* 滑块提示文本 */}
        <div className="slide-verify-text">
          {isVerified ? "验证成功" : "向右拖动滑块"}
        </div>
      </div>

      {/* 拖动事件监听 */}
      <div
        className="slide-verify-drag-area"
        onMouseMove={handleDrag}
        onMouseUp={handleDragEnd}
        onMouseLeave={handleDragEnd}
        onTouchMove={handleDrag}
        onTouchEnd={handleDragEnd}
      />
    </div>
  );
};

export default SlideVerify;
